//index.js
//获取应用实例
var app = getApp()
var baseUrl = 'http://xshop.xin/api/v1';
Page({
  data: {
    motto: 'Hello World',
    userInfo: {}
  },
  //事件处理函数
  bindViewTap: function() {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  onLoad: function () {
    console.log('onLoad')
    var that = this
    //调用应用实例的方法获取全局数据
    app.getUserInfo(function(userInfo){
      //更新数据
      that.setData({
        userInfo:userInfo
      })
    })
  }
  ,getToken: function () {
    // 调用登录接口
    wx.login({
      success: function(res) {
        var code = res.code;
        console.log('code:', code);
        wx.request({
          url: baseUrl + '/token/user',
          data: {
            code: code
          },
          method: 'POST',
          success: function(res) {
            console.log(res.data);
            wx.setStorageSync('token', res.data.token)
          },
          fail: function(res) {
            console.log(res.data);
          }
        })
      }
    })  
  }

  ,pay: function(){
    var token = wx.getStorageSync('token');
    var that = this;

    wx.request({
      url: baseUrl + '/order',
      header: {
        token: token
      },
      data: {
        products: [
          {
            product_id: 1, count: 2
          },
          {
            product_id: 2, count: 3
          }
        ]
      },
      method: 'POST',
      success: function(res){
        console.log(res.data);
        if (res.data.pass){
          wx.setStorageSync('order_id', res.data.order_id)
          that.getPreOrder(token, res.data.order_id);
        }else{
          console.log('订单未创建成功');
        }
      }
    })
  }
  ,getPreOrder: function(token, orderID){
    if(token){
      wx.request({
        url: baseUrl + '/pay/pre_order',
        method: 'POST',
        header: {
          token: token
        },
        data: {
          id: orderID
        },
        success: function(res){
          var preData = res.data;
          console.log(preData);
          return;
          wx.requestPayment({
            timeStamp: preData.timeStamp,
            nonceStr: preData.nonceStr,
            package: preData.package,
            signType: preData.signType,
            paySign: preData.paySign,
            success: function(res){
              console.log(res.data);
            },
            fail: function(error){
              console.log(error);
            }
          });
        }
      })
    }
  }
  ,checkSession: function() {// 验证微信登录状态
    wx.checkSession({
      success: function() {
        console.log('session sucess');
      },
      fail: function() {
        console.log('session fail');
      }
    })
  }
})